package cn.itcast.web.task;


import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.system.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class DeliveryNoticeTask {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Reference
    private ContractService contractService;

    @Autowired
    private UserService userService;

    public void emailNotice(){
        //查出状态为2已报运的购销合同
        ContractExample contractExample = new ContractExample();
        contractExample.createCriteria().andStateEqualTo(2);
        List<Contract> contractList = contractService.findAll(contractExample);
        //获取当前时间戳
        long now = System.currentTimeMillis();
        //创建交货期限小于3天的合同列表
        List<Contract> noticeContractList = new LinkedList<>();

        //遍历购销合同，将交货期限小于3天的合同放入创建的列表
        for (Contract contract : contractList) {
            //取出交货期限
            Date deliveryPeriod = contract.getDeliveryPeriod();
            //将交货期限的时间戳和现在的时间戳相减，若在0~1000*60*60*24*3L之间，则存入创建的列表
            if (deliveryPeriod!=null){
                long time = deliveryPeriod.getTime() - now;
                if (time<1000*60*60*24*3L&&time>0){
                    noticeContractList.add(contract);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        //遍历列表，查询user信息并使用rabbitTemplate将整合后的信息放入消息队列
        for (Contract contract : noticeContractList) {
            map.put("contractNo",contract.getContractNo());
            //通过签单人查找出用户信息
            User user = userService.findByUserName(contract.getInputBy());
            String email = user.getEmail();
            map.put("email",email);
            map.put("userName",user.getUserName());
            rabbitTemplate.convertAndSend("email-exchange","delivery.notice.email",map);
        }


    }
}
